//
//  SISSBaseWebViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/6/19.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSBaseWebViewController.h"


@interface SISSBaseWebViewController ()

/*
 *1.添加UIProgressView属性
 */
@property (nonatomic, strong) UIProgressView *progressView;

@end

@implementation SISSBaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}



- (void)setupSubviews {
    [super setupSubviews];
    
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    // 自适应屏幕宽度js
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    // 添加自适应屏幕宽度js调用的方法
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUserScript];
    wkWebConfig.userContentController = wkUController;
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];
    [self.view addSubview:webView];
    self.webView = webView;
    
    NSString *urlString;
    if ([self.url hasPrefix:@"app"] || ![self.url hasPrefix:@"http"]) {
        urlString = [NSString stringWithFormat:@"%@/%@",WEB_BASE_URL,self.url];
    } else {
        urlString = self.url;
    }
   
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.timeoutInterval = 15.0f;
    [self.webView loadRequest:request];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.left.right.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.edges.equalTo(self.view);
        }
    }];
    
    // 2.初始化progressView
    UIProgressView *progressView = [[UIProgressView alloc] init];
    progressView.backgroundColor = COLOR(0x334A60);
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view addSubview:progressView];
    self.progressView = progressView;
    
    [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.height.equalTo(@(2));
    }];
    
    // 3.添加KVO，webView有一个属性estimatedProgress，就是当前网页加载的进度，所以监听这个属性。
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)setIsHiddenProgressView:(BOOL)isHiddenProgressView {
    _isHiddenProgressView = isHiddenProgressView;
    self.progressView.hidden = isHiddenProgressView;
}

/*
 *4.在监听方法中获取网页加载的进度，并将进度赋给progressView.progress
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            
            // 添加一个简单的动画，将progressView的Height变为1.4倍
            // 动画时长0.25s，延时0.0s后开始动画
            // 动画结束后将progressView隐藏
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.8f delay:0.25f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKWKNavigationDelegate Methods

/*
 *5.在WKWebViewd的代理中展示进度条，加载完成后隐藏进度条
 */
// 开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}

// 加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    //    [SISSTools dissmiss];
    //加载完成后隐藏progressView
    //    self.progressView.hidden = YES;
}

// 加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
    //    [SISSTools showSVTitle:@"数据加载失败..." andTime:1 andColor:NO];
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}

//页面跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    //允许页面跳转
    
    NSLog(@"%@",navigationAction.request.URL);
    if (navigationAction.navigationType == WKNavigationTypeBackForward) {
        if (webView.backForwardList.backList.count == 0) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}


/*
 *6.在dealloc中取消监听
 */

- (void)dealloc {
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}



@end
